<?php
namespace app\common\model;

class MemberBankCard extends Base
{

	/**
     * 查询用户的所有银行卡
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
	public function memberBankCards($uid){
        $rows = $this->where(['uid'=>$uid])->select();
        $count = $this->where(['uid'=>$uid])->count();
        $data = [];
        if($count){
            foreach($rows as $row):
                $row = $row->toArray();
            	$row['bank_name'] = Bank::bankData($row['bank_id'])['bank_name'];
                $data[] = $row;
            endforeach;
        }

        return [
            'count' => $count,
            'data' => $data
        ];
    }

    /**
     * 查询用户的单张银行卡
     * @return [type] [description]
     */
    public function memberBankCard($uid,$cardId){
        $res = $this -> where(['uid'=>$uid,'id'=>$cardId])->find();
        if($res):
	        $res = $res -> toArray();
	        $res['bank_name'] = Bank::bankData($res['bank_id'])['bank_name'];
        endif;
        return $res;
    }
	
	public function addBank($data){
		if($this->isExist($data['uid'],$data['bank_id'],$data['bank_card'])){
			$this->error='您已经添加过该银行卡';
			return false;
		}else{
			return $this->save($data);
		}
	}

	public function setDefault($id,$uid){
		if($this->where(['id'=>$id,'uid'=>$uid])->find()){
			$this->where(['uid'=>$uid])->update(['default'=>0]);
			$this->where(['id'=>$id])->update(['default'=>1]);
		}else{
			$this->error='银行卡不存在';
			return false;
		}
	}
    
    public function isExist($uid,$bank_id,$bank_card){
    	if($this->where(['uid'=>$uid,'bank_id'=>$bank_id,'bank_card'=>$bank_card])->find()){
    		return true;
    	}else{
    		return false;
    	}
    }

}
